package com.yy.young.ums.service.impl;

import com.yy.young.common.util.CommonUtil;
import com.yy.young.common.util.StringUtils;
import com.yy.young.dal.service.IDataAccessService;
import com.yy.young.dal.util.Page;
import com.yy.young.interfaces.model.User;
import com.yy.young.interfaces.ums.model.Role;
import com.yy.young.ums.service.IUmsRoleService;
import com.yy.young.ums.util.UmsConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by Administrator on 2017/5/8.
 */
@Service("umsRoleService")
public class UmsRoleServiceImpl implements IUmsRoleService {

    @Resource(name="dataAccessService")
    IDataAccessService dataService;

    Logger logger = LoggerFactory.getLogger(UmsRoleServiceImpl.class);

    @Override
    public List<Map<String, Object>> getRoleList(Map<String, Object> parameter) throws Exception {
        return dataService.getList(UmsConstants.MAPPER.UMS_ROLE+".getRole",parameter);
    }

    @Override
    public List<Map<String, Object>> getRolePage(Map<String, Object> parameter,Page page) throws Exception {
        return dataService.getList(UmsConstants.MAPPER.UMS_ROLE+".getRole",parameter,page);
    }

    @Override
    public List<Map<String, Object>> getRoleListByCompanyId(String companyId) throws Exception {
        return dataService.getList(UmsConstants.MAPPER.UMS_ROLE+".getRoleByCompanyId", companyId);
    }

    @Override
    public int updateRole(Map<String, Object> parameter, User user) throws Exception {
        if (parameter.containsKey("TYPE")){
            //管理员角色存在管理范围
            if (UmsConstants.DICTIONARY.ROLE_TYPE_ADMIN.equals(parameter.get("TYPE"))){
                if (StringUtils.isBlank(parameter.get("RANGE_ID")+"")){//默认范围为用户的管理范围/所属单位
                    String range = user.getRangeId();
                    if (range != null && range.split(",").length > 0){
                        range = range.split(",")[0];
                    }
                    parameter.put("RANGE_ID", CommonUtil.getDefaultValue(range, user.getCompanyId()));
                }
            }else{//非管理员角色清空管理范围
                parameter.put("RANGE_ID", "");
            }
        }
        //默认角色所属单位为当前用户所属单位
        if(parameter.containsKey("COMPANY_ID") && StringUtils.isBlank(parameter.get("COMPANY_ID")+"")){
            parameter.put("COMPANY_ID", user.getCompanyId());
        }
        return dataService.update(UmsConstants.MAPPER.UMS_ROLE+".updateRole",parameter);
    }

    @Override
    public int deleteRole(Map<String, Object> parameter) throws Exception {
        String idsStr = parameter.get("ids")+"";
        if(StringUtils.isNotBlank(idsStr)){
            String[] idsArr = idsStr.split(",");
            for(String role : idsArr){
                this.deleteAuthByRole(role);//删除角色所关联的权限
                this.deleteUserByRole(role);//删除角色用户关联
                //TODO 需要发消息通知门户该角色已删除
            }
            parameter.put("ids",idsArr);
        }
        return dataService.delete(UmsConstants.MAPPER.UMS_ROLE+".deleteRole",parameter);
    }

    @Override
    public int insertRole(Map<String, Object> parameter, User user) throws Exception {
        if(StringUtils.isBlank(parameter.get("ID") + "")){
            parameter.put("ID", CommonUtil.getUUID());//默认ID为UUID
        }
        //管理员角色存在管理范围
        if (UmsConstants.DICTIONARY.ROLE_TYPE_ADMIN.equals(parameter.get("TYPE"))){
            if (StringUtils.isBlank(parameter.get("RANGE_ID")+"")){//默认范围为用户的管理范围/所属单位
                String range = user.getRangeId();
                if (range != null && range.split(",").length > 0){
                    range = range.split(",")[0];
                }
                parameter.put("RANGE_ID", CommonUtil.getDefaultValue(range, user.getCompanyId()));
            }
        }else{//非管理员角色清空管理范围
            parameter.put("RANGE_ID", "");
        }
        //默认角色所属单位为当前用户所属单位
        if(StringUtils.isBlank(parameter.get("COMPANY_ID")+"")){
            parameter.put("COMPANY_ID", user.getCompanyId());
        }
        return dataService.insert(UmsConstants.MAPPER.UMS_ROLE+".insertRole",parameter);
    }

    @Override
    public int batchInsertUser2Role(Map<String, Object> parameter) throws Exception {
        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
        String roleId = parameter.get("roleId")+"";//角色id
        String userId = parameter.get("userId")+"";//用户id,多个之间用逗号分隔
        if(StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(roleId)){
            String[] users = userId.split(",");
            for(String user : users){
                if(bRelated(user, roleId)){//如果用户和角色存在关联,则跳过
                    logger.info("[批量关联用户角色] 用户{}和角色{}存在关联关系,pass!", user, roleId);
                    continue;
                }
                Map<String,Object> map = new HashMap<String, Object>();
                map.put("ID",CommonUtil.getUUID());
                map.put("USER_ID",user);
                map.put("ROLE_ID",roleId);
                list.add(map);
            }
        }
        //当list有效时则进行插入
        if (list != null && list.size() > 0){
            return dataService.insert(UmsConstants.MAPPER.UMS_ROLE+".batchInsertRoleUser",list);
        }
        return 0;
    }

    @Override
    public int batchInsertNavigate2Role(Map<String, Object> parameter) throws Exception {
        String roleId = parameter.get("roleId")+"";//角色id
        //1.删除角色原有权限
        if(StringUtils.isNotBlank(roleId)){
            this.deleteAuthByRole(roleId);
        }
        //2.批量插入最新权限
        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
        String navigateId = parameter.get("navigateId")+"";//资源id,多个之间用逗号分隔
        if(StringUtils.isNotBlank(navigateId) && StringUtils.isNotBlank(roleId)){
            String[] sArr = navigateId.split(",");
            for(String str : sArr){
                Map<String,Object> map = new HashMap<String, Object>();
                map.put("ID",CommonUtil.getUUID());
                map.put("NAVIGATE_ID",str);
                map.put("ROLE_ID",roleId);
                list.add(map);
            }
        }
        if(list != null && list.size() > 0){//有新权限则进行批量插入权限
            return dataService.insert(UmsConstants.MAPPER.UMS_ROLE+".batchInsertRoleNavigate",list);
        }else{//没有新权限直接返回
            return 0;
        }

    }

    @Override
    public List<Map<String, Object>> getRoleListByUserId(String userId) throws Exception {
        return dataService.getList(UmsConstants.MAPPER.UMS_ROLE+".getRoleListByUserId",userId);
    }

    @Override
    public int deleteAuthByRole(String roleId) throws Exception {
        logger.info("[删除角色权限] 角色ID="+roleId);
        return dataService.delete(UmsConstants.MAPPER.UMS_ROLE+".deleteAuthByRole",roleId);
    }

    @Override
    public int deleteUserByRole(String roleId) throws Exception {
        logger.info("[删除角色用户] 角色ID="+roleId);
        return dataService.delete(UmsConstants.MAPPER.UMS_ROLE+".deleteUserByRole",roleId);
    }

    @Override
    public int batchMakeUserAndRole(String[] userIds, String[] roleIds) throws Exception {
        List<Map<String,String>> list = new ArrayList<Map<String, String>>();
        for (String uid : userIds){
            for (String rid : roleIds){
                if (bRelated(uid, rid)){
                    logger.info("[批量关联用户角色] 用户{}和角色{}存在关联关系,pass!", uid, rid);
                    continue;
                }
                Map<String,String> map = new HashMap<String, String>();
                map.put("uid", uid);
                map.put("rid", rid);
                map.put("uuid", CommonUtil.getUUID());
                list.add(map);
            }
        }
        if (list != null && list.size() > 0){
            return dataService.insert(UmsConstants.MAPPER.UMS_ROLE + ".batchMakeUserAndRole", list);
        }else{
            return 0;
        }
    }

    @Override
    public Role getRoleById(String roleId) throws Exception {
        return (Role)dataService.getObject(UmsConstants.MAPPER.UMS_ROLE + ".getRoleById", roleId);
    }

    /**
     * 判断用户和角色是否已关联
     * @param userId
     * @param roleId
     * @return
     */
    private boolean bRelated(String userId, String roleId) throws Exception{
        Map<String,String> map = new HashMap<String, String>();
        map.put("USER_ID", userId);
        map.put("ROLE_ID", roleId);
        int count = (Integer)dataService.getObject(UmsConstants.MAPPER.UMS_ROLE + ".countRoleUser", map);
        if (count > 0){//关联关系存在,返回true
            return true;
        }
        return false;
    }


}
